//
//  QSSendRemarkViewController.m
//  DigitalEconomy_iOS
//
//  Created by Ding on 2020/3/26.
//  Copyright © 2020 DingC. All rights reserved.
//

#import "QSSendRemarkViewController.h"
#import "QSSignSuccessViewController.h"
#import "QSSingInInterface.h"
#import "TZImagePickerController.h"
#import "QSSelectImageCell.h"
#import "QSOSSUploadHelper.h"
@interface QSSendRemarkViewController ()<TZImagePickerControllerDelegate, UICollectionViewDelegate, UICollectionViewDataSource, UITextViewDelegate>
@property (nonatomic, strong) NSMutableArray *picArr;
@property (nonatomic, strong) NSMutableArray *assestArray;
@property (nonatomic, assign) CGFloat itemWH;

@property (nonatomic, strong) NSArray *imageUrlArr;

@property (nonatomic, strong)NSString *imageStr;
@end
static NSString *defaultCell = @"DefaultCell";
static NSString *selectPhotoCell = @"SelectPhotoCell";
@implementation QSSendRemarkViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self configSubView];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title = @"驻企签到";
    self.remarkTextView.delegate = self;
    [self loadViewDataWithId:self.esId];
}

- (void)loadViewDataWithId:(NSString *)esid{
    if (esid) {
        [QSSingInInterface getSignInfoWithEsId:esid dBlock:^(ResponseMessage * _Nonnull rspStatusAndMessage, NSDictionary * _Nonnull result) {
            if (rspStatusAndMessage.code == kResponseSuccessCode) {
                [self setViewDataWithResult:result];
            }
        }];
    }
}

- (void)configSubView{
    self.itemWH = kRealValue(kScreenWidth - 26 - 15) / 4;
    self.collectionViewH.constant = _itemWH;
    self.submitButton.layer.cornerRadius = 22;
    self.submitButton.backgroundColor = [UIColor colorWithHexString:@"#128BEC"];
    [self.submitButton setTitleColor:[UIColor QSColorWhiteFFFFFF] forState:UIControlStateNormal];
    
    
    UICollectionViewFlowLayout *flowLaout = [[UICollectionViewFlowLayout alloc]init];
    flowLaout.scrollDirection = UICollectionViewScrollDirectionVertical;
    //上下间距
    flowLaout.minimumLineSpacing = 5;
    //左右间距
    flowLaout.minimumInteritemSpacing = 5;
    flowLaout.itemSize = CGSizeMake(_itemWH, _itemWH);
    self.collectionView.collectionViewLayout = flowLaout;
    
    [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:defaultCell];
    [self.collectionView registerClass:[QSSelectImageCell class] forCellWithReuseIdentifier:selectPhotoCell];

    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
}
//设置展示数据
- (void)setViewDataWithResult:(NSDictionary *)dic{
    NSString *dateStr = [NSString stringWithFormat:@"%@", dic[@"esTime"]];
    NSLog(@"%@",  dateStr);
    self.dateRightLabel.text = [NSDate dateWithTimestamp:dateStr format:@"yyyy-MM-dd HH:mm"];
    self.companyRightLabel.text = dic[@"companyName"];
    self.locationRightLabel.text = dic[@"esAdress"];
    self.remarkTextView.placeholder = @"请填写签到备注";
}

//提交
- (IBAction)submitAction:(UIButton *)sender {
    
    if (self.picArr.count!= 0) {
        [QSAppKeyWindow showIndeterminateHudWithText:@"正在提交"];
        [QSOSSUploadHelper asyncUploadFilesToOSS:self.picArr complete:^(NSArray<NSString *> * _Nullable names, NSError * _Nullable error) {
            [QSAppKeyWindow hideHud];
            if (!error) {
                self.imageUrlArr = names;
                [self sendSignRemarkActionWithUrlArr:self.imageUrlArr];
            }
        }];
    }else{
        [self sendSignRemarkActionWithUrlArr:self.imageUrlArr];
    }
}

- (void)sendSignRemarkActionWithUrlArr:(NSArray *)urlArr{
    NSLog(@"%ld", self.remarkTextView.text.length);
    [QSAppKeyWindow showIndeterminateHudWithText:@"正在提交"];

    if (urlArr.count) {
        for (int i = 0; i < urlArr.count; i++) {
            NSString *feedImage = urlArr[i];
            if (i == 0) {
                _imageStr = feedImage;
            } else {
                _imageStr = [NSString stringWithFormat:@"%@,%@",_imageStr,feedImage];
            }
        }
        NSLog(@"%@", _imageStr);
    }
    [QSSingInInterface insertSignRemarkWithEsid:self.esId EsRemark:_remarkTextView.text EsPic:_imageStr AndBlock:^(ResponseMessage * _Nonnull rspStatusAndMessage, NSDictionary * _Nonnull result) {
        [QSAppKeyWindow hideHud];
        if (rspStatusAndMessage.code == kResponseSuccessCode) {
            QSSignSuccessViewController *vc = [QSSignSuccessViewController new];
            vc.companyKey = [result objectForKey:@"companyKey"];
            vc.companyName = self.companyRightLabel.text;
            vc.signId = (NSString *)[result objectForKey:@"esId"];
            vc.townshipId =  (NSString *)[result objectForKey:@"townshipId"];
            vc.townshipName = (NSString *)[result objectForKey:@"townshipName"];
            [self.navigationController pushViewController:vc animated:YES];
        }
    }];
}
#pragma mark - UICollectionViewDelegate
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{    
    if (self.picArr.count == 9) {
        return self.picArr.count;
    }else{
        return _picArr.count + 1;
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (_picArr.count < 9 && indexPath.item == self.picArr.count)  {
        //小于9 点击到添加
        TZImagePickerController *imagePicker = [[TZImagePickerController alloc] initWithMaxImagesCount:9 delegate:self];
        [imagePicker setSortAscendingByModificationDate:NO];
        imagePicker.selectedAssets = _assestArray;
        imagePicker.allowPickingVideo = NO;
        [[UIViewController currentViewController] presentViewController:imagePicker animated:YES completion:nil];
    }else{
        TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithSelectedAssets:_assestArray selectedPhotos:_picArr index:indexPath.row];
        [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        }];
        [[UIViewController currentViewController] presentViewController:imagePickerVc animated:YES completion:nil];
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (_picArr.count < 9 && indexPath.item == self.picArr.count) {
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:defaultCell forIndexPath:indexPath];
        UIImageView *pic = [[UIImageView alloc]initWithFrame:cell.contentView.frame];
        //    [pic sd_setImageWithURL:[NSURL URLWithString:_picArr[indexPath.item]]];
        pic.image = [UIImage imageNamed:@"icon_addimage"];
        pic.contentMode = UIViewContentModeScaleAspectFit;
        [cell.contentView addSubview:pic];
        return cell;
    }else{
        QSSelectImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:selectPhotoCell forIndexPath:indexPath];
        [cell.imagev setImage:self.picArr[indexPath.row]];
        cell.deleteButton.hidden = NO;
        cell.deleteButton.tag = indexPath.item;
        [cell.deleteButton addTarget:self action:@selector(deletePhotos:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }
}
#pragma mark - TZImagePickerControllerDelegate

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto{
    self.picArr = [NSMutableArray arrayWithArray:photos];
//    [self checkPhotosCountWithAddImage];
    self.assestArray = [NSMutableArray arrayWithArray:assets];
    if (_picArr.count >= 0 && _picArr.count <= 3) {
        self.collectionViewH.constant = _itemWH;
    }
    if (_picArr.count >= 4 && _picArr.count <= 7 ) {
        self.collectionViewH.constant = _itemWH *2 + 5;
    }
    if (_picArr.count >= 8) {
        self.collectionViewH.constant = _itemWH *3 + 10;
    }
//    _isSelectOriginalPhoto = isSelectOriginalPhoto;
    [_collectionView reloadData];
}

//删除图片数组的某一张
- (void)deletePhotos:(UIButton *)sender{
    [self.picArr removeObjectAtIndex:sender.tag];
    [self.assestArray removeObjectAtIndex:sender.tag];
    
    [self.collectionView reloadData];
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [super touchesEnded:touches withEvent:event];
    [self.view endEditing:YES];
}

#pragma mark - UITextViewDelegate
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if (text.length == 0) return YES;//允许删除。
    if (textView.text.length >= 140) {
        return NO;
    }else{
        return YES;
    }
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
